#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys

sys.path.append('..')
from common_utils import CBBCommonUtils


def get_plugin_info():
    plugin_info = {
        "name": "centos_security_audit_006 Reinforce_auth_log_configuration",
        "plugin_id": "centos_security_audit_006",
        "plugin_type": "Security Audit",
        "info": "Check and reinforce SU command usage log configuration",
        "level": "C",
        "module": "Safety reinforcement",
        "author": "fanyi",
        "keyword": "Safety reinforcement",
        "configable": "false"
    }
    return plugin_info


logger = None
cur_user = None
cur_module = None
cur_task = None


def set_plugin_logger(setter, user, module, task, *args, **kwargs):
    global logger, cur_user, cur_module, cur_task
    logger = setter
    cur_user = user
    cur_module = module
    cur_task = task


# 扫描函数
def scan(ip, sys_user, sys_pwd, flag=0):
    des_list = []
    error_count = 0
    log_flag = -1
    ng_flag = -1
    logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', "Scan Start.")
    # 获取syslog-ng当前状态
    cmd = "service syslog-ng status | grep -E \"Active|Loaded\""
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    # 检错，每次执行命令都会进行检错，并决定返回退出/继续执行
    if not result or (len(result) == 1 and "Redirecting to" in result[0]):
        # 检查是否安装syslog-ng服务及配置文件
        if output and "not-found" not in output[0]:
            cmd = "cat /etc/syslog-ng/syslog-ng.conf | grep facility\\(authpriv\\) | grep -v or | grep -v \\#"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            if not result and len(output) != 0:
                des_list.append("syslog-ng is safe")
                logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', "syslog-ng is safe.")
                ng_flag = -1
            elif not result and len(output) == 0:
                error_count += 1
                des_list.append("syslog-ng log not configured")
                logger.debug_warning(cur_user, cur_module, cur_task+'_Scan', '', "syslog-ng log not configured.")
                ng_flag = 1
            else:
                error_des = "CMD process ERROR. Error info: {}".format(result[0].replace("\n", ""))
                des_list.append(error_des)
                logger.debug_error(cur_user, cur_module, cur_task+'_Scan', '', error_des)
                error_count += 1
                return des_list, error_count
        else:
            set_des = "syslog-ng service Not Installed."
            des_list.append(set_des)
            logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', set_des)
            ng_flag = -1
    elif len(result) != 1:
        set_des = "syslog-ng service Not Installed."
        des_list.append(set_des)
        logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', set_des)
        ng_flag = -1
    else:
        error_des = "CMD process ERROR. Error info: {}".format(result[0].replace("\n", ""))
        des_list.append(error_des)
        logger.debug_error(cur_user, cur_module, cur_task+'_Scan', '', error_des)
        error_count += 1
        return des_list, error_count
    # 获取rsyslog当前状态
    cmd = "service rsyslog status | grep -E \"Active|Loaded\""
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    # 检错，每次执行命令都会进行检错，并决定返回退出/继续执行
    if not result or (len(result) == 1 and "Redirecting to" in result[0]):
        # 检查是否安装rsyslog服务及配置文件
        if output and "not-found" not in output[0]:
            cmd = "cat /etc/rsyslog.conf | grep authpriv.[*] | grep -v \\#"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            if not result and len(output) != 0:
                des_list.append("rsyslog is safe")
                logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', "rsyslog is safe.")
                log_flag = -1
            elif not result and len(output) == 0:
                error_count += 1
                des_list.append("rsyslog log not configured")
                logger.debug_warning(cur_user, cur_module, cur_task+'_Scan', '', "rsyslog log not configured.")
                log_flag = 1
            else:
                error_des = "CMD process ERROR. Error info: {}".format(result[0].replace("\n", ""))
                des_list.append(error_des)
                logger.debug_error(cur_user, cur_module, cur_task+'_Scan', '', error_des)
                error_count += 1
                return des_list, error_count
        else:
            set_des = "rsyslog service Not Installed."
            des_list.append(set_des)
            logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', set_des)
            log_flag = -1
    elif len(result) != 1:
        set_des = "rsyslog service Not Installed."
        des_list.append(set_des)
        logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', set_des)
        log_flag = -1
    else:
        error_des = "CMD process ERROR. Error info: {}".format(result[0].replace("\n", ""))
        des_list.append(error_des)
        logger.debug_error(cur_user, cur_module, cur_task+'_Scan', '', error_des)
        error_count += 1
        return des_list, error_count
    des_list.append("Scan Complete.")
    logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', "Scan Complete.")
    # 是否加固
    if flag == 1 and ((log_flag == 1 or log_flag == 0) or (ng_flag == 1 or ng_flag == 0)):
        reinforce_des, reinforce_err = reinforce(ip, sys_user, sys_pwd, log_flag, ng_flag)
        if reinforce_err == 0:
            error_count = 0
            des_list.extend(reinforce_des)
        else:
            error_count += 1
            des_list.extend(reinforce_des)
    return des_list, error_count


# 加固函数
def reinforce(ip, sys_user, sys_pwd, log_flag, ng_flag):
    des_list = []
    error_count = 0
    log_result = []
    ng_result = []
    logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Start.")
    # 组装命令
    if log_flag == 1 or log_flag == 0:
        log_result, log_error = logReinforce(ip, sys_user, sys_pwd)
    if ng_flag == 1 or ng_flag == 0:
        ng_result, ng_error = ngReinforce(ip, sys_user, sys_pwd)
    des_list.extend(log_result)
    des_list.extend(ng_result)
    des_list.append("Reinforce Complete.")
    logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Complete.")
    return des_list, error_count


#rsyslog服务加固函数
def logReinforce(ip, sys_user, sys_pwd):
    des_list = []
    error_count = 0
    logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "rsyslog Reinforce Start.")
    safe_cmd = "cat /etc/rsyslog.conf | grep authpriv.[*] | grep -v \\#"
    result, target_output = CBBCommonUtils.cbb_run_cmd(ip, safe_cmd, username=sys_user, passwd=sys_pwd)
    if not result and not target_output:
        # 检查是否存在可能被覆盖的备份文件
        check_cmd = "ls /etc | grep rsyslog.conf.SuLog.`date +%Y-%m-%d`"
        check_result, check_output = CBBCommonUtils.cbb_run_cmd(ip, check_cmd, username=sys_user, passwd=sys_pwd)
        if not check_result and len(check_output) != 0:
            result = []
        else:
            # 备份文件
            cmd = "cp /etc/rsyslog.conf /etc/rsyslog.conf.SuLog.`date +%Y-%m-%d`"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
        if not result:
            # 检查是否备份成功
            check_cmd = "ls /etc | grep rsyslog.conf.SuLog.`date +%Y-%m-%d`"
            check_result, check_output = CBBCommonUtils.cbb_run_cmd(ip, check_cmd, username=sys_user, passwd=sys_pwd)
            if not check_result and len(check_output) != 0:
                logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "Backup Succeed.")
            else:
                error_count += 1
                backup_check_des = "Backup check FAILED."
                des_list.append(backup_check_des)
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', backup_check_des)
                return des_list, error_count
        else:
            error_count += 1
            des_list.append("Backup Failed.")
            logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Backup Failed.")
            return des_list, error_count
        # 加固
        cmd = "sed -i '/# ### begin forwarding rule ###/i # The authpriv file has restricted access.\\nauthpriv.*                                              /var/log/secure\\n' /etc/rsyslog.conf"
        result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
        if not result:
            # 查看是否修改成功
            check_cmd = "cat /etc/rsyslog.conf | grep authpriv.[*] | grep -v \\#"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, check_cmd, username=sys_user, passwd=sys_pwd)
            if not result and len(output) != 0:
                cmd = "service rsyslog restart"
                result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            elif not result and len(output) == 0:
                error_count += 1
                des_list.append("Reinforce Error.")
                logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Error.")
                # 加固失败，回滚
                rollback_des, rollback_err = rollback(ip, sys_user, sys_pwd)
                if rollback_err == 0:
                    des_list.extend(rollback_des)
                else:
                    error_count += 1
                    des_list.extend(rollback_des)
                return des_list, error_count
            else:
                error_count += 1
                des_list.append("Check Failed.")
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Check Failed.")
        else:
            error_count += 1
            des_list.append("Check Failed.")
            logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Check Failed.")
            # 加固失败，回滚
            rollback_des, rollback_err = rollback(ip, sys_user, sys_pwd)
            if rollback_err == 0:
                des_list.extend(rollback_des)
            else:
                error_count += 1
                des_list.extend(rollback_des)
            return des_list, error_count
    elif not result and len(target_output) != 0:
        des_list.append("It is Safe.")
        logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "It is Safe.")
    else:
        error_count += 1
        des_list.append("Reinforce Failed.")
        logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Failed.")
        # 加固失败，回滚
        rollback_des, rollback_err = rollback(ip, sys_user, sys_pwd)
        if rollback_err == 0:
            des_list.extend(rollback_des)
        else:
            error_count += 1
            des_list.extend(rollback_des)
        return des_list, error_count
    log_file_result, log_file_error = logFileReinforce(ip, sys_user, sys_pwd)
    des_list.extend(log_file_result)
    des_list.append("rsyslog Reinforce Complete.")
    logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "rsyslog Reinforce Complete.")
    return des_list, error_count


#syslog-ng服务加固函数
def ngReinforce(ip, sys_user, sys_pwd):
    des_list = []
    error_count = 0
    logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "syslog-ng Reinforce Start.")
    safe_cmd = "cat /etc/syslog-ng/syslog-ng.conf | grep facility\\(authpriv\\) | grep -v or | grep -v \\#"
    result, target_output = CBBCommonUtils.cbb_run_cmd(ip, safe_cmd, username=sys_user, passwd=sys_pwd)
    if not result and len(target_output) != 3:
        # 检查是否存在可能被覆盖的备份文件
        check_cmd = "ls /etc/syslog-ng | grep syslog-ng.conf.SuLog.`date +%Y-%m-%d`"
        check_result, check_output = CBBCommonUtils.cbb_run_cmd(ip, check_cmd, username=sys_user, passwd=sys_pwd)
        if not check_result and len(check_output) != 0:
            result = []
        else:
            # 备份文件
            cmd = "cp /etc/syslog-ng/syslog-ng.conf /etc/syslog-ng/syslog-ng.conf.SuLog.`date +%Y-%m-%d`"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
        if not result:
            # 检查是否备份成功
            check_cmd = "ls /etc/syslog-ng | grep syslog-ng.conf.SuLog.`date +%Y-%m-%d`"
            check_result, check_output = CBBCommonUtils.cbb_run_cmd(ip, check_cmd, username=sys_user, passwd=sys_pwd)
            if not check_result and len(check_output) != 0:
                logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "Backup Succeed.")
            else:
                error_count += 1
                backup_check_des = "Backup check FAILED."
                des_list.append(backup_check_des)
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', backup_check_des)
                return des_list, error_count
        else:
            error_count += 1
            des_list.append("Backup Failed.")
            logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Backup Failed.")
            return des_list, error_count
        # 加固
        try:
            cmd = "cat /etc/syslog-ng/syslog-ng.conf | grep ^destination"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            if len(result) != 0:
                error_count += 1
                des_list.append("Reinforce Error.")
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Error.")
                return des_list, error_count
            cmd = "red -i '/" + output[len(output)-1] + "/a destination d_auth { file(\"/var/log/secure\"); };' /etc/syslog-ng/syslog-ng.conf"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            if len(result) != 0:
                error_count += 1
                des_list.append("Reinforce Error.")
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Error.")
                return des_list, error_count

            cmd = "cat /etc/syslog-ng/syslog-ng.conf | grep ^filter"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            if len(result) != 0:
                error_count += 1
                des_list.append("Reinforce Error.")
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Error.")
                return des_list, error_count
            cmd = "red -i '/" + output[len(output)-1] + "/a filter f_auth { facility(authpriv); };' /etc/syslog-ng/syslog-ng.conf"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            if len(result) != 0:
                error_count += 1
                des_list.append("Reinforce Error.")
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Error.")
                return des_list, error_count

            cmd = "cat /etc/syslog-ng/syslog-ng.conf | grep ^source"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            if len(result) != 0:
                error_count += 1
                des_list.append("Reinforce Error.")
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Error.")
                return des_list, error_count
            output = output.split()
            src_code = output[1]
            cmd = "cat /etc/syslog-ng/syslog-ng.conf | grep ^log"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            if len(result) != 0:
                error_count += 1
                des_list.append("Reinforce Error.")
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Error.")
                return des_list, error_count
            cmd = "red -i '/" + output[len(output)-1] + "/a log { source(" + src_code + "); filter(f_auth); destination(d_auth); };' /etc/syslog-ng/syslog-ng.conf"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            if len(result) != 0:
                error_count += 1
                des_list.append("Reinforce Error.")
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Error.")
                return des_list, error_count

            cmd = "service syslog-ng restart"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            if len(result) != 0:
                error_count += 1
                des_list.append("Reinforce Error.")
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Error.")
                return des_list, error_count

            log_file_result, log_file_error = logFileReinforce(ip, sys_user, sys_pwd)
            des_list.extend(log_file_result)
            des_ng = "syslog-ng Reinforce Complete."
            des_list.append(des_ng)
            logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', des_ng)
            return des_list, error_count
        except Exception as er:
            error_count += 1
            des_ng = "syslog-ng Reinforce FAILED:{}.".format(str(er))
            des_list.append(des_ng)
            logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', des_ng)
            # 加固失败，回滚
            rollback_des, rollback_err = rollback(ip, sys_user, sys_pwd)
            if rollback_err == 0:
                des_list.extend(rollback_des)
            else:
                error_count += 1
                des_list.extend(rollback_des)
            return des_list, error_count
    elif not result and len(target_output) == 3:
        des_list.append("It is Safe.")
        logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "It is Safe.")
        return des_list, error_count
    else:
        error_count += 1
        des_list.append("Reinforce Failed.")
        logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Failed.")
        # 加固失败，回滚
        rollback_des, rollback_err = rollback(ip, sys_user, sys_pwd)
        if rollback_err == 0:
            des_list.extend(rollback_des)
        else:
            error_count += 1
            des_list.extend(rollback_des)
        return des_list, error_count


# 日志文件处理函数
def logFileReinforce(ip, sys_user, sys_pwd):
    des_list = []
    error_count = 0
    logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "Process log file.")
    cmd = "touch /var/log/secure"
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    if not result:
        cmd = "ls /var/log | grep secure"
        result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
        if not result and len(output) != 0:
            cmd = "chmod 775 /var/log/secure"
            result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
            if not result:
                set_des = "make log file Succeed."
                des_list.append(set_des)
                logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', set_des)
                return des_list, error_count
            else:
                set_des = "Chmod Error."
                des_list.append(set_des)
                logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', set_des)
                return des_list, error_count
        else:
            set_des = "check log file Error."
            des_list.append(set_des)
            logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', set_des)
            return des_list, error_count
    else:
        set_des = "make log file Error."
        des_list.append(set_des)
        logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', set_des)
        return des_list, error_count


# 回滚函数
def rollback(ip, sys_user, sys_pwd):
    des_list = []
    error_count = 0
    log_flag = -1
    ng_flag = -1
    log_result = []
    ng_result = []
    logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', "Rollback Start.")
    # 获取syslog-ng当前状态
    cmd = "service syslog-ng status | grep -E \"Active|Loaded\""
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    if not result or (len(result) == 1 and "Redirecting to" in result[0]):
        # 检查是否安装syslog-ng服务
        if output and "not-found" not in output[0]:
            if "running" in output[1]:
                ng_flag = 1
            else:
                ng_flag = 0
        else:
            ng_flag = -1
    elif len(result) != 1:
        ng_flag = -1
    else:
        error_des = "CMD process ERROR. Error info: {}".format(result[0].replace("\n", ""))
        des_list.append(error_des)
        logger.debug_error(cur_user, cur_module, cur_task+'_Rollback', '', error_des)
        error_count += 1
        return des_list, error_count
    # 获取rsyslog当前状态
    cmd = "service rsyslog status | grep -E \"Active|Loaded\""
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    if not result or (len(result) == 1 and "Redirecting to" in result[0]):
        # 检查是否安装rsyslog服务
        if output and "not-found" not in output[0]:
            if "running" in output[1]:
                log_flag = 1
            else:
                log_flag = 0
        else:
            log_flag = -1
    elif len(result) != 1:
        log_flag = -1
    else:
        error_des = "CMD process ERROR. Error info: {}".format(result[0].replace("\n", ""))
        des_list.append(error_des)
        logger.debug_error(cur_user, cur_module, cur_task+'_Rollback', '', error_des)
        error_count += 1
        return des_list, error_count
    # 组装命令
    if log_flag == 1 or log_flag == 0:
        log_result, log_error = logRollback(ip, sys_user, sys_pwd)
    if ng_flag == 1 or ng_flag == 0:
        ng_result, ng_error = ngRollback(ip, sys_user, sys_pwd)
    des_list.extend(log_result)
    des_list.extend(ng_result)
    return des_list, error_count


# rsyslog回滚函数
def logRollback(ip, sys_user, sys_pwd):
    des_list = []
    error_count = 0
    logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', "rsyslog Rollback Start.")
    # 查找备份文件，此处的查找支持多备份文件的查找（结果会按时间顺序排序），并默认回滚最新一次备份的内容，可以连续多次回滚
    grep_cmd = "ls /etc | grep rsyslog.conf.SuLog.*"
    result, output = CBBCommonUtils.cbb_run_cmd(ip, grep_cmd, username=sys_user, passwd=sys_pwd)
    if not result and len(output) != 0:
        target = output[len(output) - 1].replace("\n", "")
        cmd = "/bin/cp -rf /etc/" + target + " /etc/rsyslog.conf"
    else:
        error_count += 1
        des_list.append("rsyslog Backup file NOT FOUND.")
        logger.debug_error(cur_user, cur_module, cur_task+'_Rollback', '', "rsyslog backup file not found.")
        return des_list, error_count
    # 回滚文件
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    if not result:
        logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', "rsyslog Rollback Succeed.")
        del_cmd = "rm -rf /etc/" + target
        # 删除对应的备份文件
        result, output = CBBCommonUtils.cbb_run_cmd(ip, del_cmd, username=sys_user, passwd=sys_pwd)
        if not result:
            del_des = "rsyslog Backup file deleted. Target is {}.".format(target)
            logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', del_des)
        else:
            error_count += 1
            del_des = "rsyslog Backup file delete FAILED."
            des_list.append(del_des)
            logger.debug_error(cur_user, cur_module, cur_task+'_Rollback', '', del_des)
            return des_list, error_count
    else:
        error_count += 1
        des = "rsyslog Rollback FAILED, please retry."
        des_list.append(des)
        logger.debug_error(cur_user, cur_module, cur_task+'_Rollback', '', des)
        return des_list, error_count
    des_list.append("rsyslog Rollback Complete.")
    logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', "rsyslog Rollback Complete.")
    return des_list, error_count


# syslog-ng回滚函数
def ngRollback(ip, sys_user, sys_pwd):
    des_list = []
    error_count = 0
    logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', "syslog-ng Rollback Start.")
    # 查找备份文件，此处的查找支持多备份文件的查找（结果会按时间顺序排序），并默认回滚最新一次备份的内容，可以连续多次回滚
    grep_cmd = "ls /etc/syslog-ng | grep syslog-ng.conf.SuLog.*"
    result, output = CBBCommonUtils.cbb_run_cmd(ip, grep_cmd, username=sys_user, passwd=sys_pwd)
    if not result and len(output) != 0:
        target = output[len(output) - 1].replace("\n", "")
        cmd = "/bin/cp -rf /etc/syslog-ng/" + target + " /etc/syslog-ng/syslog-ng.conf"
    else:
        error_count += 1
        des_list.append("syslog-ng Backup file NOT FOUND.")
        logger.debug_error(cur_user, cur_module, cur_task+'_Rollback', '', "syslog-ng Backup file not found.")
        return des_list, error_count
    # 回滚文件
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    if not result:
        logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', "syslog-ng Rollback Succeed.")
        del_cmd = "rm -rf /etc/syslog-ng/" + target
        # 删除对应的备份文件
        result, output = CBBCommonUtils.cbb_run_cmd(ip, del_cmd, username=sys_user, passwd=sys_pwd)
        if not result:
            del_des = "syslog-ng Backup file deleted. Target is {}.".format(target)
            logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', del_des)
        else:
            error_count += 1
            del_des = "syslog-ng Backup file delete FAILED."
            des_list.append(del_des)
            logger.debug_error(cur_user, cur_module, cur_task+'_Rollback', '', del_des)
            return des_list, error_count
    else:
        error_count += 1
        des = "syslog-ng Rollback FAILED, please retry."
        des_list.append(des)
        logger.debug_error(cur_user, cur_module, cur_task+'_Rollback', '', des)
        return des_list, error_count
    des_list.append("syslog-ng Rollback Complete.")
    logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', "syslog-ng Rollback Complete.")
    return des_list, error_count


def check(ip, *args, **kwargs):
    sys_user = kwargs.get("system_user")
    sys_pwd = kwargs.get("system_pwd")
    comm = kwargs.get("command")
    try:
        des_list = []
        logger.debug_info(cur_user, cur_module, cur_task+'_Check', '', "centos_security_audit_006 Start")
        if comm == 1:
            des_scan, error_scan = scan(ip, sys_user, sys_pwd, flag=0)
            des_list.extend(des_scan)
            step_error = int(error_scan)
        elif comm == 2:
            des_reinforce, error_reinforce = scan(ip, sys_user, sys_pwd, flag=1)
            des_list.extend(des_reinforce)
            step_error = int(error_reinforce)
        elif comm == 3:
            des_rollback, error_rollback = rollback(ip, sys_user, sys_pwd)
            des_list.extend(des_rollback)
            step_error = int(error_rollback)
        else:
            return {"code": 3, "count": 0, "des": ['command must be 1/2/3']}
        logger.debug_info(cur_user, cur_module, cur_task+'_Check', '', "centos_security_audit_006 Complete")
        if step_error == 0:
            code = 0
        elif step_error <= -1:
            code = 2
        else:
            code = 1
        return {"code": code, "count": step_error, "des": des_list}
    except Exception as er:
        code = 1
        des = ["ERROR:", str(er)]
        logger.debug_error(cur_user, cur_module, cur_task+'_Check', '', des)
        return {"code": code, "count": 0, "des": des}


# check(ip="100.2.91.150", system_user="root", system_pwd="admin", command=0, flag=0)
